<?php
namespace app\common\service;

use think\Model;

class CounselorRankService extends BaseService
{

    /**
     * 添加或修改等级
     * @param $sid
     * @param $name
     * @return int
     */
    public function saveRank($sid, $name, $counselor_rank_id = 0){
        if($counselor_rank_id > 0){
            return db('counselor_rank')->where(['sid' => $sid, 'counselor_rank_id' => $counselor_rank_id])->update(['name' => $name]);
        } else {
            $data = [
                'sid' => $sid,
                'name' => $name,
                'add_time' => time()
            ];
            return db('counselor_rank')->insert($data);
        }
    }

    /**
     * 删除顾问等级
     * @param $sid
     * @param $counselor_rank_id
     * @return array
     */
    public function deleteRank($sid, $counselor_rank_id){
        //查询是否已使用
        $where = [
            'sid' => $sid,
            'counselor_status' => 1,
            'counselor_rank_id' => $counselor_rank_id
        ];
        $info = db('user_integral')->where($where)->find();
        if(!empty($info)){
           return ['status' => 0, 'msg' => '改顾问等级正在使用，无法删除'];
        }

        $result = db('counselor_rank')->where(['sid' => $sid, 'counselor_rank_id' => $counselor_rank_id])->setField('status', -1);
        return $result === false ? ['status' => 0, 'msg' => '删除失败'] : ['status' => 1, 'msg' => '删除成功'];
    }

    /**
     * 获取等级列表
     * @param $sid
     */
    public function getRankList($sid){
        $list_count = db('counselor_rank')->where(['sid' => $sid, 'status' => 1])->count();
        $list = db('counselor_rank')->field('counselor_rank_id,name')->where(['sid' => $sid, 'status' => 1])->order('add_time DESC')->select();
        return ['content' => $list,'page' => ['count' => $list_count]];
    }

    /**
     * 获取等级详情
     * @param $sid
     * @param $counselor_rank_id
     * @return array|false|\PDOStatement|string|Model
     */
    public function getRankDetail($sid, $counselor_rank_id){
        $where = [
            'sid' => $sid,
            'counselor_rank_id' => $counselor_rank_id,
            'status' => 1
        ];
        $data['content'] = db('counselor_rank')->field('counselor_rank_id,name')->where($where)->find();
        return $data;
    }
    /**
     * 获取等级名称
     * @param $sid
     * @param $counselor_rank_id
     * @return array|false|\PDOStatement|string|Model
     */
    public function getRankName($sid, $counselor_rank_id){
        $res = $this->getRankDetail($sid, $counselor_rank_id);
        return $res['content']['name'];
    }

    public function setCounselorRank($sid,$counselor_rank_id,$postParam){
        $where = [
            'sid' => $sid
        ];
        return db('user_integral')->where($where)->whereIn('userid',$postParam['uid'])->update(['counselor_rank_id' => $counselor_rank_id]);
    }
}